<?php

namespace app\admin\controller\saler;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Request;
use PHPExcel_IOFactory;
use PHPExcel;

/**
 * 客户群组列管理
 *
 * @icon fa fa-circle-o
 */
class Groupinfo extends Backend
{

    /**
     * SalerGroupInfo模型对象
     * @var \app\admin\model\SalerGroupInfo
     */
    protected $model = null;
    protected $noNeedLogin = ['count_group', 'test'];

    public function test()
    {
        $jobs=Db::name('task_job')->where('tid', 1153)->select();
        foreach ($jobs as $job){
            Db::name('task_job')->where("id",$job['id'])->setField('number',trim($job['number']));
        }
    }

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('SalerGroupInfo');
//        $this->count_group();
    }

    public function count_group()
    {
//        var_dump(str_replace(' ', '',"13456789839       "));
        $groups = Db::name('saler_group')->order('id desc')->limit(50)->select();
        foreach ($groups as $group) {
            $this->count_group_by_id($group['id']);
        }
    }

    private function count_group_by_id($id)
    {
        try {
            $count = Db::name('saler_group_info')->where('saler_group_id', $id)->count();
            Db::name('saler_group')->where('id', $id)->setField('count', $count);
        } catch (Exception $e) {
            ;
        }
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    $request = Request::instance();
                    $saler_group_id = $request->get('saler_group_id');

                    if(!$saler_group_id){
                        $this->error('系统错误');
                    }

                    if(!$params['tel']){
                        $this->error('请输入联系方式');
                    }

                    $tel = str_replace(' ', '', $params['tel']);
                    $tel = str_replace('-', '', $tel);
                    $tel = trim($tel);

                    //不符合格式的数据
                    if (!preg_match("/^1[345678]{1}\d{9}$/", $tel) && !preg_match("/^([0-9]{3,4})?[0-9]{7,8}$/", $tel)) {
                        $this->error('联系方式格式不正确');
                    }

                    $salerId = Db::name('saler')
                        ->where('tel',$tel)
                        ->value('id');

                    if(!$salerId){
                        //如果不存在，插入客户池，插入群组
                        $salerId = Db::name('saler')
                            ->insertGetId([
                                'name'      => $params['name']?:'客户',
                                'admin_id'  => $this->auth->id,
                                'tel'       => $tel,
                                'createtime'=>time(),
                            ]);
                        Db::name('saler_group_info')
                            ->insert([
                                'saler_group_id'    => $saler_group_id,
                                'saler_id'          => $salerId,
                            ]);
                        $this->count_group_by_id($saler_group_id);
                        $this->success();
                    }

                    $groupInfo = Db::name('saler_group_info')
                        ->where('saler_group_id',$saler_group_id)
                        ->where('saler_id',$salerId)
                        ->find();

                    if($groupInfo){
                        $this->error('该客户信息已在群组中');
                    }

                    Db::name('saler_group_info')
                        ->insert([
                            'saler_group_id'    => $saler_group_id,
                            'saler_id'          => $salerId,
                        ]);
                    $this->count_group_by_id($saler_group_id);
                    $this->success();




                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = basename(str_replace('\\', '/', get_class($this->model)));
//                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
//                        $this->model->validate($validate);
//                    }
//                    $saler_group_id = Request::instance()->get('saler_group_id');
//                    $params['saler_group_id'] = $saler_group_id;
//                    if (0 == $this->model->where($params)->count()) {
//                        $result = $this->model->allowField(true)->save($params);
//                        $this->count_group_by_id($saler_group_id);
//                        if ($result !== false) {
//                            $this->success();
//                        } else {
//                            $this->error($this->model->getError());
//                        }
//                    } else {
//                        $this->error("联系人重复");
//                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


//    public function line_edit()
//    {
////        if ($this->request->isPost())
////        {
//            $request = Request::instance();
//            $name   = $request->get('name');
//            $tel    = $request->get('tel');
//
//            $salerId      = $request->get('saler_id');
//            $salerGroupId = $request->get('saler_group_id');
//
//            if(!$salerId || !$salerGroupId){
//                return json(['code'=>0,'msg'=>'系统错误']);
//            }
//
//            if(isset($name))
//            {
//                Db::name('saler')
//                    ->where('id',$salerId)
//                    ->update(['name'=>$name]);
//                return json(['code'=>200,'msg'=>'执行成功']);
//            }
//
//            if(isset($tel))
//            {
//                $tel = str_replace(' ', '', $tel);
//                $tel = str_replace('-', '', $tel);
//                $tel = trim($tel);
//
//                //不符合格式的数据
//                if (!preg_match("/^1[345678]{1}\d{9}$/", $tel) && !preg_match("/^([0-9]{3,4})?[0-9]{7,8}$/", $tel)) {
//                    $this->error('联系方式格式不正确');
//                }
//
//                $salerId = Db::name('saler')
//                    ->where('tel',$tel)
//                    ->value('id');
//
//            }
//
////        }
//    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $saler_group_id = Request::instance()->get('saler_group_id');
                $this->count_group_by_id($saler_group_id);
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
//        var_dump(Request::instance()->get('saler_group_id'));
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                foreach ($word as $k => $v) {
                    foreach ($searchfield as $m => $n) {
                        $query->where($n, "like", "%{$v}%", $andor);
                    }
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field("{$primarykey},{$field}")
                ->field("password,salt", true)
                ->select();
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 查看
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['saler', 'salergroup'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['saler', 'salergroup'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {

                $row->getRelation('saler')->visible(['id', 'admin_id', 'name', 'tel','company','tts_format']);
                $row->getRelation('salergroup')->visible(['id', 'name']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['json']= (object)json_decode(($value['saler']['tts_format']));
            }

            $result = array("total" => $total, "rows" => $list);

            $saler_group_id = Request::instance()->get('saler_group_id');
            $this->count_group_by_id($saler_group_id);
            return json($result);
        }
        return $this->view->fetch();
    }


    function export()
    {

        $saler_group_id = Request::instance()->get("saler_group_id");

        $name = '错误日志';
        $data = Db::name('saler_failed')
            ->where('saler_group_id', $saler_group_id)
            ->where('admin_id', $this->auth->id)
            ->select();


        $excel = new \PHPExcel(); //引用phpexcel
        iconv('UTF-8', 'gb2312', $name); //针对中文名转码
        $header = ['错误原因', '名称', '电话']; //表头,名称可自定义
        $excel->setActiveSheetIndex(0);
        $excel->getActiveSheet()->setTitle($name); //设置表名
        $excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(50);

        $letter = ['A', 'B', 'C'];//列坐标

        //生成表头
        for ($i = 0; $i < count($header); $i++) {
            //设置表头值
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", $header[$i]);
            //设置表头字体样式
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName('宋体');
            //设置表头字体大小
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(14);
            //设置表头字体是否加粗
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
//            //设置表头文字水平居中
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            //设置文字上下居中
//            $excel->getActiveSheet()->getStyle($letter[$i])->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            //设置单元格背景色
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->getStartColor()->setARGB('FFFFFFFF');
////            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->getStartColor()->setARGB('FF6DBA43');
//            //设置字体颜色
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB('FFFFFFFF');
        }

        //写入数据
        foreach ($data as $k => $v) {
            //从第二行开始写入数据（第一行为表头）
            $excel->getActiveSheet()->setCellValue('A' . ($k + 2), $v['note']);
            $excel->getActiveSheet()->setCellValue('B' . ($k + 2), $v['name']);
            $excel->getActiveSheet()->setCellValue('C' . ($k + 2), $v['tel']);
        }


//        //清理缓冲区，避免中文乱码
//        ob_end_clean();
//        header('Content-Type: application/vnd.ms-excel');
//        header('Content-Disposition: attachment;filename="'.$name.'.xls"');
//        header('Cache-Control: max-age=0');
//
//        //导出数据
//        $res_excel = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
//        $res_excel->save('php://output');


        header('Content-type: application/vnd.ms-excel;charset=utf-8;name="' . $name . '.xls"');
        header("Content-Disposition: attachment; filename=$name.xls");
        header('Cache-Control: max-age=0');

        header('Pragma: public');
        $res_excel = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $res_excel->save('php://output');


    }

    public function groupDetail()
    {
        $groupId = $this->request->get('saler_group_id');
        if(!$groupId)
        {
            $this->error('参数错误');
        }
        $data = Db::name('saler')
            ->alias('s')
            ->join('saler_group_info i','i.saler_id = s.id')
            ->where('i.saler_group_id',$groupId)
            ->find();
        if(!$data || !$data['tts_format'])
        {
            $data=Db::name('saler')
                    ->find();
            $data['tts_format'] = [];
        }
        return json($data);
    }

    public function import()
    {

        $saler_group_id = Request::instance()->get("saler_group_id");

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }


        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        //将超出2个字段的表的信息存入特定的字段
        $fields = array_filter($fields);
        $columnNum = count($fields);

        if($columnNum > 13)
        {
            $this->error('最多只能添加十个字段');
        }

        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }

            $arr = [];
            if($columnNum>3){
                for ($i=3;$i<$columnNum;$i++){
                    $arr[$fields[$i]] =$values[$i];
                }
            }
            $ttsFormat = json_encode($arr);
            //var_dump($this->auth->id);
            $admin_id = $this->auth->id;
//            $temp = array_combine(array('name', 'tel'), $values);
            //去掉固话号码中的 -
            if (isset($values)) {
                $values[1] = str_replace(' ', '', $values[1]);
                $values[1] = str_replace('-', '', $values[1]);
                $values[1] = str_replace('（', '', $values[1]);
                $values[1] = str_replace('）', '', $values[1]);
                $values[1] = str_replace('(', '', $values[1]);
                $values[1] = str_replace(')', '', $values[1]);
                $values[1] = str_replace('*', '', $values[1]);
                $values[1] = str_replace('#', '', $values[1]);
                $values[1] = str_replace('{', '', $values[1]);
                $values[1] = str_replace('}', '', $values[1]);
                $values[1] = str_replace('|', '', $values[1]);
                $values[1] = str_replace('+86', '', $values[1]);
            }
            if(isset($values[2]))
            {
                $temp = array_combine(array('name', 'tel','company'), array($values[0], $values[1],$values[2]));
            }else{
                $temp = array_combine(array('name', 'tel'), array($values[0], $values[1]));
            }

            $values[1] = trim($values[1]);
            //不符合格式的数据删掉
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $values[1]) && !preg_match("/^0\d{9,11}$/", $values[1])) {

                $check = Db::name('saler_failed')->where('tel', $values[1])->find();
                if (!$check) {
                    Db::name('saler_failed')->insert([
                        'admin_id' => $this->auth->id,
                        'name' => $temp['name'],
                        'tel' => $temp['tel'],
                        'saler_group_id' => $saler_group_id,
                        'note' => '格式不正确',
                        'created_at' => date('Y-m-d H:i:s')

                    ]);
                }
                unset($values);
                continue;
            }


//            var_dump($temp);
            $saler_id = Db::name("saler")
                ->where('admin_id', $admin_id)
//                ->where('name', $temp['name']) //只以电话作为客户的唯一标示
                ->where('tel', $temp['tel'])
                ->value('id');
            if (is_null($saler_id)) {
                if(isset($temp['company']))
                {
                    $saler_id = Db::name('saler')->insertGetId(array('admin_id' => $admin_id, 'name' => $temp['name'], 'tel' => $temp['tel'],'company'=>$temp['company'],'tts_format'=>$ttsFormat));
                }else{
                    $saler_id = Db::name('saler')->insertGetId(array('admin_id' => $admin_id, 'name' => $temp['name'], 'tel' => $temp['tel'],'tts_format'=>$ttsFormat));
                }

            }else{
                if($ttsFormat){
                    if(isset($temp['company']))
                    {
                        Db::name('saler')->where('id',$saler_id)
                            ->update(['company'=>$temp['company'],'tts_format'=>$ttsFormat]);
                    }else{
                        Db::name('saler')->where('id',$saler_id)
                            ->update(['tts_format'=>$ttsFormat]);
                    }

                }

            }
            if ($temp) {
                //$insert[] = $temp;
                $id = Db::name("saler_group_info")
                    ->where('saler_id', $saler_id)
                    ->where('saler_group_id', $saler_group_id)
                    ->value('id');
                $saler_group = array('saler_id' => $saler_id, 'saler_group_id' => $saler_group_id);
                if (is_null($id)) {
                    if (!in_array($saler_group, $insert)) {
                        $insert[] = $saler_group;
                    }
                }
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }
        $this->count_group_by_id($saler_group_id);
        $this->success();
    }


}
